package com.hh.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.constant.RoleConstant;
import com.hh.entity.SysRole;
import com.hh.mapper.SysRoleMapper;
import com.hh.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author 辉辉
 * @since 2022-08-15
 */
@Service
@Slf4j
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Resource
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询角色的列表
     * @return
     */
    @Override
    public List<SysRole> list() {
        log.info("全查询角色列表");
        String roleStr = redisTemplate.opsForValue().get(RoleConstant.ROLE_PREFIX);
        List<SysRole> sysRoleList = null;
        if (StringUtils.isEmpty(roleStr)) {
            // 查询数据库
            sysRoleList = sysRoleMapper.selectList(null);
            if (CollectionUtils.isEmpty(sysRoleList)) {
                return Collections.emptyList();
            }
            redisTemplate.opsForValue().set(RoleConstant.ROLE_PREFIX, JSON.toJSONString(sysRoleList), Duration.ofDays(7));
        } else {
            sysRoleList = JSON.parseArray(roleStr, SysRole.class);
        }
        return sysRoleList;
    }
}
